import BASE_URL from '@/utils/env.js' //引入接口共用地址
import {getToken, removeAvatarUrl, removeExpiresIn, removeNickName, removeToken} from "@/utils/auth";
import errorCode from "@/utils/errorCode";
export const request = (options) => {
    return new Promise((resolve, reject) => {
        // 获取用户令牌
        const isToken = (options.header || {}).isToken === false
        let header = {}

        if (getToken() && !isToken) {
            header = {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer '+ getToken(),
            }
            // options.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        uni.request({
            url: (BASE_URL + options.url).trim(), //接收请求的API
            method: options.method || 'GET', //接收请求的方式,如果不传默认为GET
            data: options.data || {}, //接收请求的data,不传默认为空
            header: header, //接收请求的header
            success(res) {
                const code = res.data.code || 200;
                // 获取错误信息
                const msg = errorCode[code] || res.data.msg || errorCode['default']
                if (code === 401) {
                    uni.showToast({title: "登录已过期，请重新登录", icon: "none", position: 'top'})
                    removeExpiresIn()
                    removeAvatarUrl()
                    removeToken()
                    removeNickName()
                    uni.navigateTo({url: '/pages/my/login'})
                    return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
                } else if (code === 500) {
                    uni.showToast({title: msg, icon: "none", position: 'top'})
                    return Promise.reject(new Error(msg))
                } else if (code === 601) {
                    uni.showToast({title: msg, icon: "none", position: 'top'})
                    return Promise.reject('error')
                } else if (code !== 200) {
                    uni.showToast({title: msg, icon: "none", position: 'top'})
                    return Promise.reject('error')
                } else {
                    resolve(res.data) // 使用resolve将数据传递出去
                }
            },
            fail: (err) => {
                console.log(err)
                // console.log('err' + err.error)
                // if (message == "Network Error") {
                //     message = "后端接口连接异常";
                // } else if (message.includes("timeout")) {
                //     message = "系统接口请求超时";
                // } else if (message.includes("Request failed with status code")) {
                //     message = "系统接口" + message.substr(message.length - 3) + "异常";
                // }

                reject(err)
            }
        })
    })
}
